import 'package:f_enjoy_plus_community/pages/home/index.dart';
import 'package:f_enjoy_plus_community/pages/mine/index.dart';
import 'package:f_enjoy_plus_community/utils/eventbus.dart';
import 'package:f_enjoy_plus_community/utils/token.dart';
import 'package:flutter/material.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 当前页的索引值.私有
  int _currentIndex = 0;
  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "首页",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png",
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png",
    },
  ];

  //处理数据.提供一个barItemList方法
  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
          icon: Image.asset(item['default'], width: 32, height: 32),
          activeIcon: Image.asset(item['active'], width: 32, height: 32),
          label: item['title'],
        ),
      );
    }
    return items;
  }

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });


    //注册登录页面
    eventBus.on<LogoutEvent>().listen((event){
      print("跳转登录页面====准备跳转");
      Navigator.pushNamed(context,'/login');
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //注意遮挡导航栏的安全区域
      body: SafeArea(
        //IndexedStack是根据索引切换界面.类似Actvity中切换Fragment
        child: IndexedStack(
          //table的索引值
          index: _currentIndex,
          children:  [HomePage(), MinePage(index:_currentIndex)],
        ),
      ),
      //底部导航条
      bottomNavigationBar: BottomNavigationBar(
        //设置切换动画
        type: BottomNavigationBarType.shifting,
        //设置选中时的元素标号
        currentIndex: _currentIndex,
        //设置选中时的颜色
        selectedItemColor: Color.fromARGB(255, 85, 145, 175),
        //设置未选中时的颜色
        unselectedItemColor: Colors.black,
        items: barItemList(),
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}
